package com.hiabr.iep.common.web.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.hiabr.iep.common.web.handler.TenantHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;

import javax.annotation.Resource;

@Configuration
public class MyBatisPlusConfig {

    @Lazy
    @Resource
    private TenantProperties tenantProperties;

    /**
     * MyBatisPlus拦截器（用于分页）
     */
    @Bean
    public MybatisPlusInterceptor paginationInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 租户拦截器必须放在分页拦截器前，因为租户拦截器会先处理SQL，然后分页拦截器才会处理SQL
        // 添加MySQL的租户拦截器、
        if (tenantProperties.isEnable()) {
            interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(
                    new TenantHandler(
                            tenantProperties.getIgnoreTable(),
                            tenantProperties.getIdColumn(),
                            tenantProperties.isAdminEnable()
                    )));
        }
        //添加MySQL的分页拦截器
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}
